package com.example.lesson

import androidx.annotation.Nullable
import com.example.core.http.EntityCallback
import com.example.core.http.HttpClient.get
import com.example.core.utils.toast
import com.example.lesson.entity.Lesson
import com.google.gson.reflect.TypeToken
import java.util.ArrayList


class LessonPresenter {

    //用伴生对象的成员来代替静态成员
    companion object {
        private const val LESSON_PATH = "lessons"
    }

    private var activity: LessonActivity? = null

    constructor(activity: LessonActivity?) {
        this.activity = activity
    }

    private var lessons: List<Lesson> = ArrayList()

    private val type = object : TypeToken<List<Lesson?>?>() {}.type

    fun fetchData() {
        get(LESSON_PATH, type, object : EntityCallback<List<Lesson?>> {

            override fun onSuccess(entity: List<Lesson?>) {
                this@LessonPresenter.lessons = lessons
                activity!!.runOnUiThread { activity!!.showResult(lessons) }
            }

            override fun onFailure(@Nullable message: String?) {
                activity!!.runOnUiThread { toast(message!!) }
            }

        })
    }

    fun showPlayback() {
        val playbackLessons = arrayListOf<Lesson>()
//        for (lesson in lessons) {
//            if (lesson?.state === Lesson.State.PLAYBACK) {
//                playbackLessons.add(lesson)
//            }
//        }


//        lessons.forEach {
//            if (it.state === Lesson.State.PLAYBACK) {
//                playbackLessons.add(it)
//            }
//        }
//        activity!!.showResult(playbackLessons)

//        val filter = lessons.filter { it.state === Lesson.State.PLAYBACK }
//        activity!!.showResult(filter)
        activity!!.showResult(lessons.filter { it.state === Lesson.State.PLAYBACK })
    }

}